<?php

/**
 * 后台文章model操作
 * @author  xiaobai
 * @date    2017-01-08
 */

namespace app\common\model;

use app\common\model\Common;

class News extends Common
{
    
    protected $pk = 'id';
    protected $autoWriteTimestamp = 'datetime'; // 自动写入时间，格式为Y-m-d H:i:s

    const IS_TOP_NO     = 0;    // 否
    const IS_TOP_ALWAYS = 1;    // 永久置顶
    const IS_TOP_SPELL  = 2;    // 时间段置顶
    const ORIGINAL_YES  = 1;    // 是原创文章
    const ORIGINAL_NO   = 0;    // 不是原创文章
    const STATUS_ISSUE  = 1;    // 状态，发布
    const STATUS_DRAFT  = 0;    // 状态，草稿箱
    const EDITOR_NORMAL = 1;    // 普通富文本编辑器
    const EDITOR_MARK   = 2;    // Markdown 编辑器

    protected static function init()
    {
        News::beforeInsert(function ($news) {
            return $news->admin_id = session('admin_id');
        });
    }

    public static $is_tops = array(
        self::IS_TOP_NO     => '否',
        self::IS_TOP_ALWAYS => '永久置顶',
        self::IS_TOP_SPELL  => '时间段置顶'
    );

    public static $is_original = array(
        self::ORIGINAL_YES => '是',
        self::ORIGINAL_NO  => '否',
    );

    public static $editors = [
        self::EDITOR_NORMAL => '普通富文本',
        self::EDITOR_MARK   => 'Markdown',
    ];

    /**
     * 获取热门文章，访问数量多的文章
     * @param int $limit        获取数量
     * @param int $cache_time   缓存时间
     * @return array|false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getHotNewsData($limit = 6, $cache_time = 0)
    {
        $key  = 'getHotNewsData_'.$limit;
        $list = cache($key);
        if (empty($list)) {
            $where = ['status'=>self::STATUS_ISSUE];
            $list  = $this->where($where)->order('read_number desc, id desc')->limit($limit)->select();
            if (!empty($list)) {
                $cache_time = !empty($cache_time) ? $cache_time : 3600*24*7;
                cache($key, $list, $cache_time);
            }
        }

        return $list;
    }

    /**
     * 获取上一篇下一篇文章信息
     * @param int $new_id       当前页面文章id
     * @param int $column_id    所属栏目id
     * @param string $type      类型：up上一篇；down下一篇
     * @param int $cache_time   缓存时间
     * @return array|false|mixed|null|\PDOStatement|string|\think\Model
     */
    public function getUpDownNews($new_id = 0, $column_id = 0, $type = 'up', $cache_time = 3600*24*7)
    {
        $order   = 'id desc';
        $where[] = ['column_id', '=', $column_id];
        if ($type == 'up') {
            $where[] = ['id', '<', $new_id];
        } else {
            $where[] = ['id', '>', $new_id];
            $order   = 'id asc';
        }
        $key = 'getUpDownNews_'.md5(json_encode($where));
        $row = cache($key);
        if (empty($row)) {
            $row = $this->where($where)->order($order)->find();
            if (!empty($row)) {
                cache($key, $row, $cache_time);
            } else {
                $row = [];
            }
        }
        return $row;
    }
}
